package web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.Member;
import beans.TypeMessage;
import beans.Typer;
import service.MemberService;
import service.TypeMessageService;
import service.TypeService;
import serviceimpl.MemberServiceIpmt;
import serviceimpl.TypeMessageServiceIpml;
import serviceimpl.TypeServiceIpmt;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.接收请求、获得参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");


		// 2.封装javabean
		// 3.调用service，获得结果
		MemberService ms = new MemberServiceIpmt();
		try {
			Member member = ms.login(username, password);
			request.getSession().setAttribute("member", member);
			String auto = request.getParameter("autoLogin");

			if ("on".equals(auto)) {
				// 保存账号密码到cookie
				// 解决中文问题
//						URLEncoder.encode(username,"utf-8");
				Cookie nameCookie = new Cookie("username", username);
				Cookie pwdCookie = new Cookie("password", password);

				nameCookie.setMaxAge(Integer.MAX_VALUE);
				pwdCookie.setMaxAge(Integer.MAX_VALUE);
				nameCookie.setPath(request.getContextPath());
				pwdCookie.setPath(request.getContextPath());

				response.addCookie(nameCookie);
				response.addCookie(pwdCookie);
			}
			
			// 4.指定jsp显示
			response.sendRedirect("/zzLoveProduct/SuccessServlet");
		} catch (Exception e) {
			// 登陆失败
			request.setAttribute("exception",e);
//			response.sendRedirect("/zzLoveProduct/login/login/login.jsp");
			request.getRequestDispatcher("/login/login/login.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
